import jwt
import datetime
from django.conf import settings


class JwtToken:
	def __init__(self):
		self.secret_key = "settings.SECRET_KEY"
		self.access_token_expire = 3600  # 访问token有效期1小时
		self.refresh_token_expire = 86400  # 刷新token有效期24小时

	def generate_tokens(self, user_id):
		"""生成access token和refresh token"""
		# 创建access token
		access_payload = {
			'user_id': user_id,
			'type': 'access',
			'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=self.access_token_expire),
			'iat': datetime.datetime.utcnow()
		}
		access_token = jwt.encode(access_payload, self.secret_key, algorithm='HS256')

		# 创建refresh token
		refresh_payload = {
			'user_id': user_id,
			'type': 'refresh',
			'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=self.refresh_token_expire),
			'iat': datetime.datetime.utcnow()
		}
		refresh_token = jwt.encode(refresh_payload, self.secret_key, algorithm='HS256')

		return access_token, refresh_token

	def verify_token(self, token):
		"""验证token并返回 payload"""
		try:
			payload = jwt.decode(token, self.secret_key, algorithms=['HS256'])
			return True, payload
		except jwt.ExpiredSignatureError:
			return False, "Token已过期"
		except jwt.InvalidTokenError:
			return False, "无效的Token"


# 创建JWT工具实例
jwt_tool = JwtToken()

# # 测试代码
# jwtt = jwt_tool.generate_tokens(1)
# print(jwtt)
# print(jwt_tool.verify_token(jwtt[0]))